package com.lnsf.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lnsf.dao.IStockDao;
import com.lnsf.dbutils.DataAccess;
import com.lnsf.model.Stock;

public class StockDaoImpl implements IStockDao {

	@Override
	public List<Stock> select() {
		List<Stock> list = new ArrayList<Stock>();
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("select * from stock");
			rs = prep.executeQuery();
			while (rs.next()) {
				Stock stock = new Stock(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4),rs.getDate(5));
				list.add(stock);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(rs, prep, conn);
		}
		return list;
	}

	@Override
	public int insert(Stock stock) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("insert into stock values (null, ?, ?, ?,sysdate())");
			prep.setInt(1, stock.getShId());
			prep.setInt(2, stock.getgId());
			prep.setInt(3, stock.getStNum());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int update(Stock stock) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("update stock set shId = ? ,gId=?,stNum=?,purchaseDate=? where stId = ?");
			prep.setInt(1, stock.getShId());
			prep.setInt(2, stock.getgId());
			prep.setInt(3, stock.getStNum());
			prep.setDate(4,(Date) stock.getPurchaseDate());
			prep.setInt(5, stock.getStId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int delete(Stock stock) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("delete from users where stId = ?");
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

}
